import { useState, useEffect, useRef } from 'react';
import { Button, Space, Modal, Form, Checkbox, Input, InputNumber, message, Select } from 'antd';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import { FormattedMessage, useIntl } from 'umi';
import request from '@/utils/request';
import CateComp from '@/components/CategoryComponent';
import { WhseSelect, WhseBinSelect } from '@/components/FormItemSelect';

const { confirm } = Modal;
const apiURL = '/api/services/app/DMRActn/';
const ViewPage = (props: any) => {
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState<any>({});
  const [freshNum, setFreshNum] = useState(1);
  const [defaultWhse, setDefaultWhse] = useState('DJK');
  const formRef = useRef<any>(null);
  const intl = useIntl();

  useEffect(() => {
    props.onRef(this);
    if (props.data) {
      setData(props.data);
      formRef.current.setFieldsValue({ model: props.data });
    }
  }, [props.data]);

  const onFinish = (values: any) => {
    save(values.model);
  };

  const save = (model: any) => {
    let act = 'New';
    const method = 'POST';
    if (model.id) {
      act = 'Modify';
    }
    if (model.actionType === 'accept' && (!model.warehouseCode || !model.binNum)) {
      message.error(intl.formatMessage({ id: 'pages.whsebin.required' }));
      return;
    }
    setLoading(true);
    request(apiURL + act, {
      method,
      data: model,
    }).then((response) => {
      if (response) {
        if (response.success) {
          message.success(intl.formatMessage({ id: 'pages.save.success' }));
          formRef.current.setFieldsValue({ model: response.result });
          props.refreshData(model.dmrNum);
        }
        setLoading(false);
      }
    });
  };

  const delObj = () => {
    confirm({
      title: intl.formatMessage({ id: 'pages.warning' }),
      icon: <ExclamationCircleOutlined />,
      content: intl.formatMessage({ id: 'pages.delete.confirm' }),
      onOk() {
        request(apiURL + 'DelBatch', {
          method: 'POST',
          data: [data.id],
        }).then((response) => {
          if (response) {
            if (response.success) {
              formRef.current.resetFields();
              props.refreshData(data.packSlip);
            }
          }
        });
      },
    });
  };

  const changeActType = (e: any) => {
    const whse = e === 'debit' ? 'DJK' : 'YJK';
    setFreshNum(freshNum + 1);
    setDefaultWhse(whse);
    formRef.current.setFieldsValue({
      model: {
        warehouseCode: whse,
        binNum: '1',
      },
    });
  };

  const selectBin = (e: any) => {
    setFreshNum(freshNum + 1);
  };

  const layout = {
    labelCol: { span: 5 },
    wrapperCol: { span: 16 },
  };

  return (
    <Form {...layout} ref={formRef} onFinish={onFinish}>
      <Form.Item name={['model', 'id']} hidden={true}>
        <Input />
      </Form.Item>
      <Form.Item name={['model', 'lotNum']} hidden={true}>
        <Input />
      </Form.Item>
      <Form.Item
        label={<FormattedMessage id="pages.dmrNum" />}
        name={['model', 'dmrNum']}
        rules={[{ required: true }]}
      >
        <Input disabled style={{ width: 100 }} />
      </Form.Item>
      <Form.Item label={<FormattedMessage id="pages.partNum" />}>
        <Input.Group compact>
          <Form.Item
            noStyle
            name={['model', 'partNum']}
            rules={[{ required: true, message: <FormattedMessage id="pages.partNum.required" /> }]}
          >
            <Input style={{ width: 150 }} disabled />
          </Form.Item>
          <Form.Item noStyle name={['model', 'ium']}>
            <Input style={{ width: 80 }} placeholder="IUM" disabled />
          </Form.Item>
        </Input.Group>
      </Form.Item>
      <Form.Item
        name={['model', 'partDescription']}
        label={<FormattedMessage id="pages.partDescription" />}
        rules={[
          { required: true, message: intl.formatMessage({ id: 'pages.partDescription.required' }) },
        ]}
      >
        <Input disabled />
      </Form.Item>
      <Form.Item
        name={['model', 'quantity']}
        label={<FormattedMessage id="pages.quantity" />}
        rules={[{ required: true, message: intl.formatMessage({ id: 'pages.quantity.required' }) }]}
      >
        <InputNumber />
      </Form.Item>
      <Form.Item
        name={['model', 'actionType']}
        label={<FormattedMessage id="pages.actionType" />}
        rules={[
          { required: true, message: intl.formatMessage({ id: 'pages.actionType.required' }) },
        ]}
      >
        <Select onChange={changeActType}>
          <Select.Option value="accept">
            <FormattedMessage id="pages.action.accept" />
          </Select.Option>
          <Select.Option value="debit">
            <FormattedMessage id="pages.action.debit" />
          </Select.Option>
        </Select>
      </Form.Item>
      <CateComp
        layout="reasonCode"
        width={200}
        name={['model', 'reasonCode']}
        label={<FormattedMessage id="pages.reasonCode" />}
      />
      <Form.Item
        label={<FormattedMessage id="pages.inWarehouseCode" />}
        style={{ marginBottom: 0 }}
      >
        <Input.Group compact>
          <WhseSelect
            width={120}
            rules={[
              { required: true, message: <FormattedMessage id="pages.warehouseCode.required" /> },
            ]}
            showSearch={true}
            name={['model', 'warehouseCode']}
            placeholder={<FormattedMessage id="pages.inWarehouseCode" />}
            params={{ keywords: defaultWhse }}
            setCurrent={(e: any) => selectBin(e)}
            freshNum={freshNum}
          />
          <WhseBinSelect
            width={120}
            rules={[{ required: true, message: <FormattedMessage id="pages.binNum.required" /> }]}
            showSearch={true}
            name={['model', 'binNum']}
            placeholder={<FormattedMessage id="pages.binNum" />}
            params={{ whse: defaultWhse }}
            freshNum={freshNum}
          />
        </Input.Group>
      </Form.Item>
      <Form.Item wrapperCol={{ offset: 5 }} name={['model', 'openDMR']} valuePropName="checked">
        <Checkbox disabled>
          <FormattedMessage id="pages.openline" />
        </Checkbox>
      </Form.Item>
      <Form.Item wrapperCol={{ offset: layout.labelCol.span }}>
        <Space>
          <Button key="1" type="primary" htmlType="submit" loading={loading}>
            <FormattedMessage id="pages.save" />
          </Button>
          <Button key="2" danger disabled={!data.id} onClick={delObj}>
            <FormattedMessage id="pages.delete" />
          </Button>
        </Space>
      </Form.Item>
    </Form>
  );
};

export default ViewPage;
